package com.ghp.admin.aop;

import com.ghp.admin.annotation.AuthCheck;
import com.ghp.admin.service.UserService;
import com.ghp.common.exception.BusinessException;
import com.ghp.common.utils.ThreadLocalUtils;
import com.ghp.common.utils.ThrowUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.ghp.common.utils.response.ResponseStatus.CLIENT_UNAUTHORIZED_ERROR;

/**
 * @author ghp
 * @title 权限校验
 * @description
 */
@Aspect
@Component
public class AuthCheckAspect {

    @Resource
    private UserService userService;

    /**
     * 执行拦截
     *
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 获取当前登录用户对应的角色
        String userRole = userService.getById(ThreadLocalUtils.getCurrentId()).getUserRole();
        // 判断权限是否一致
        ThrowUtils.throwIf(!mustRole.equals(userRole),
                new BusinessException(CLIENT_UNAUTHORIZED_ERROR));
        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}

